import { Button } from "@chakra-ui/react";
import { Stack } from "@chakra-ui/react";
import { useToast } from "@chakra-ui/react";
import { useQueryClient } from "react-query";
import {
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalFooter,
  ModalBody,
  ModalCloseButton,
} from "@chakra-ui/react";
import {
  FormControl,
  FormLabel,
  FormErrorMessage,
  Input,
} from "@chakra-ui/react";
import { Form, Formik } from "formik";
import * as Yup from "yup";

const CommentSchema = Yup.object({
  score:Yup.number()
  .min(0,"请输入0~5之间的数字")
  .max(5,"请输入0~5之间的数字")
  .required("请输入0~5之间的数字"),
});

export const CompleteModal: React.FC<{
  isOpen: boolean;
  onClose: () => void;
  appId:  string;
  missionId: string;
}> = ({
  isOpen,
  onClose,
  appId,
  missionId,
}) => {
  const toast = useToast();
  const queryClient = useQueryClient();
  return (
    <Modal isOpen={isOpen} onClose={onClose}>
      <ModalOverlay />
      <ModalContent>
        <Formik
          initialValues={{
            score: 5,
          }}
          validationSchema={CommentSchema}
          onSubmit={(values, actions) => {
            fetch(`/api/application/${appId}/complete`, {
              method: "PUT",
              body: JSON.stringify({
                score: values.score,
              }),
              headers: {
                "content-type": "application/json",
                Authorization:
                  "Bearer " + String(localStorage.getItem("accessToken")),
              },
            })
              .then((res) => {
                if (res.ok) {
                  toast({ title: "完成任务成功" });
                  queryClient.invalidateQueries(`mission/${missionId}`);
                  window.location.reload();
                  return res.json();
                } else {
                  toast({ title: "完成任务失败" });
                  actions.setSubmitting(false);
                }
              })
              .catch((err) => {
                toast({ title: "完成任务失败", description: err.message });
                actions.setSubmitting(false);
              });
          }}
        >
          {(formik) => (
            <Form>
              <ModalHeader>评价</ModalHeader>
              <ModalBody>
                <Stack>
                  <FormControl
                    isInvalid={
                      formik.touched.score &&
                      Boolean(formik.errors.score)
                    }
                  >
                    <FormLabel htmlFor="score">评价分数(5分制)</FormLabel>
                    <Input
                      id="score"
                      onChange={formik.handleChange}
                      value={formik.values.score}
                    />
                    <FormErrorMessage>
                      {formik.errors.score}
                    </FormErrorMessage>
                  </FormControl>
                </Stack>
              </ModalBody>
              <ModalFooter>
                <Button
                  colorScheme="primary"
                  mr={3}
                  type="submit"
                  isLoading={formik.isSubmitting}
                >
                  确定
                </Button>
                <Button variant="ghost" onClick={onClose}>
                  取消
                </Button>
              </ModalFooter>
              <ModalCloseButton />
            </Form>
          )}
        </Formik>
      </ModalContent>
    </Modal>
  );
};
